package com.lancoo.znbkxx.teacher.ui.activity

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.os.AsyncTask
import android.view.View
import android.widget.ImageView
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.base.BaseViewModel
import com.lancoo.znbkxx.teacher.databinding.ActivitySimpleDetailPlayerBinding
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import kotlinx.android.synthetic.main.activity_simple_detail_player.*
import java.io.File
import java.io.FileInputStream
import java.io.IOException

/**
 * @author : wealive
 * @date   : 2020/6/28 16:01
 * @desc   :
 */
class VideoPlayerActivity : BaseVMActivity<BaseViewModel, ActivitySimpleDetailPlayerBinding>() {
     val videoPath by lazy { intent.getStringExtra("VideoPath") }
    lateinit var imageView: ImageView
    lateinit var orientationUtils: OrientationUtils
    private var isPlay = false
    private var isPause = false

    override fun setLayoutID(): Int {
        return R.layout.activity_simple_detail_player
    }

    override fun providerVMClass(): Class<BaseViewModel>? {
        return BaseViewModel::class.java
    }

    override fun initView() {
        //增加封面
        imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        //增加title
        detail_player.titleTextView.visibility = View.GONE
        detail_player.backButton.visibility = View.GONE
        //外部辅助的旋转，帮助全屏
        orientationUtils = OrientationUtils(this, detail_player)
        //初始化不打开外部的旋转
        orientationUtils.isEnable = false
        //加载视频第一帧
        BitmapAsyncTask().execute()
    }

    private fun showVideoPlayer() {
        val gsyVideoOption = GSYVideoOptionBuilder()
        gsyVideoOption.setThumbImageView(imageView)
            .setIsTouchWiget(true)
            .setRotateViewAuto(false)
            .setLockLand(false)
            .setAutoFullWithSize(false)
            .setShowFullAnimation(false)
            .setNeedLockFull(true)
            .setUrl(videoPath)
            .setCacheWithPlay(true)
            .setVideoTitle("")
            .setNeedShowWifiTip(false)
            .setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onPrepared(url: String, vararg objects: Any) {
                    super.onPrepared(url, *objects)
                    //开始播放了才能旋转和全屏
                    orientationUtils.isEnable = true
                    isPlay = true
                }

                override fun onQuitFullscreen(
                    url: String,
                    vararg objects: Any
                ) {
                    super.onQuitFullscreen(url, *objects)
                    orientationUtils.backToProtVideo()
                }
            }).setLockClickListener { view, lock ->
                orientationUtils.isEnable = !lock
            }.build(detail_player)
        detail_player.fullscreenButton
            .setOnClickListener(View.OnClickListener { //直接横屏
                orientationUtils.resolveByClick()
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detail_player.startWindowFullscreen(this, true, true)
            })
    }

    fun goBack(view: View?) {
        orientationUtils.backToProtVideo()
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        finish()
    }

    fun getNetVideoBitmap(videoUrl: String): Bitmap? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            //根据url获取缩略图
            //retriever.setDataSource(videoUrl, new HashMap());
            try {
                if (videoUrl.contains("http")) {
                    retriever.setDataSource(videoUrl, HashMap())
                } else {
                    val inputStream =
                        FileInputStream(File(videoUrl).absolutePath)
                    retriever.setDataSource(inputStream.fd)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime(
                2000000,
                MediaMetadataRetriever.OPTION_CLOSEST_SYNC
            ) //这个时间就是第一秒的
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } finally {
            retriever.release()
        }
        return bitmap
    }

    @SuppressLint("StaticFieldLeak")
    inner class BitmapAsyncTask : AsyncTask<String, Int, Bitmap?>() {
        override fun doInBackground(vararg strings: String): Bitmap? {
            // 在doInBackground方法中执行耗时操作
            //加载视频第一帧
            return getNetVideoBitmap(videoPath)
        }

        override fun onPostExecute(bitmap: Bitmap?) {
            super.onPostExecute(bitmap)
            // 在onPostExecute方法中进行ui操作
            imageView.setImageBitmap(bitmap) //对应的ImageView赋值图片
            showVideoPlayer()
        }
    }

    override fun onBackPressed() {
        orientationUtils.backToProtVideo()
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }


    override fun onPause() {
        detail_player.currentPlayer.onVideoPause()
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        detail_player.currentPlayer.onVideoResume(false)
        super.onResume()
        isPause = false
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isPlay) {
            detail_player.currentPlayer.release()
        }
        orientationUtils.releaseListener()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detail_player.onConfigurationChanged(this, newConfig, orientationUtils, true, true)
        }
    }
}